<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      v-loading="loading"
      :model="postForm"
      :rules="rules"
      class="form-container"
    >
      <sticky :z-index="10" :class-name="'sub-navbar '+postForm.blogStatus">
        <!-- 是否允许评论 -->
        <CommentDropdown v-model="postForm.enableComment" />
        <PlatformDropdown v-model="postForm.blogTags" />
        <SourceUrlDropdown v-model="postForm.source_uri" />
        <el-button
          v-loading="loading"
          style="margin-left: 10px;"
          type="success"
          @click="submitForm"
        >Publish</el-button>
        <el-button v-loading="loading" type="warning" @click="draftForm">Draft</el-button>
      </sticky>

      <div class="createPost-main-container">
        <el-row>
          <Warning />

          <el-col :span="24">
            <el-form-item style="margin-bottom: 40px;" prop="title">
              <MDinput v-model="postForm.blogTitle" :maxlength="100" name="name" required>Title</MDinput>
            </el-form-item>

            <div class="postInfo-container">
              <el-row>
                <!-- 作者 -->
                <el-col :span="8">
                  <el-form-item label-width="60px" label="Author:" class="postInfo-container-item">
                    <el-select
                      v-model="postForm.createUser"
                      :remote-method="getRemoteUserList"
                      clearable
                      filterable
                      default-first-option
                      remote
                      placeholder="Search user"
                    >
                      <el-option
                        v-for="(item,index) in userListOptions"
                        :key="item+index"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <!-- 发布时间 -->
                <el-col :span="10">
                  <el-form-item
                    label-width="120px"
                    label="Publish Time:"
                    class="postInfo-container-item"
                  >
                    <el-date-picker
                      v-model="displayTime"
                      type="datetime"
                      format="yyyy-MM-dd HH:mm:ss"
                      placeholder="Select date and time"
                    />
                  </el-form-item>
                </el-col>
                <!-- 重要度 -->
                <el-col :span="6">
                  <el-form-item
                    label-width="90px"
                    label="Importance:"
                    class="postInfo-container-item"
                  >
                    <el-rate
                      v-model="postForm.importance"
                      :max="3"
                      :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                      :low-threshold="1"
                      :high-threshold="3"
                      style="display:inline-block"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <!-- 标签 -->
                <el-col :span="8">
                  <el-form-item label-width="60px" label="Tags:" class="postInfo-container-item">
                    <DynamicTags :tag-arr="postForm.blogTags" />
                  </el-form-item>
                </el-col>
                <!-- 文章路径 -->
                <el-col :span="10">
                  <el-form-item label-width="120px" label="文章路径:" class="postInfo-container-item">
                    <el-input v-model="postForm.blogSubUrl"></el-input>
                  </el-form-item>
                </el-col>
                <!-- 是否允许评论 -->
                <!-- <el-col :span="6">
                  <el-form-item label-width="90px" label="允许评论:" class="postInfo-container-item">
                    <el-switch v-model="postForm.enableComment">
                    </el-switch>
                  </el-form-item>
                </el-col>-->
                <!-- 分类 -->
                <el-col :span="6">
                  <el-form-item label-width="90px" label="分类:" class="postInfo-container-item">
                    <el-select
                      v-model="postForm.blogCategoryId"
                      :remote-method="getBlogCategory"
                      clearable
                      filterable
                      default-first-option
                      remote
                      placeholder="选择分类"
                    >
                      <el-option
                        v-for="(item) in categoryMapOptions"
                        :key="item.categoryId"
                        :label="item.categoryName"
                        :value="item.categoryId"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </el-col>
        </el-row>

        <!-- 摘要，总结 -->
        <el-form-item style="margin-bottom: 40px;" label-width="70px" label="Summary:">
          <el-input
            v-model="postForm.blogTitle"
            :rows="1"
            type="textarea"
            class="article-textarea"
            autosize
            placeholder="Please enter the content"
          />
          <span v-show="contentShortLength" class="word-counter">{{ contentShortLength }}words</span>
        </el-form-item>

        <!-- 内容 -->
        <el-form-item prop="content" style="margin-bottom: 30px;" class="postInfo-container-item">
          <!-- 富文本编辑器 -->
          <!-- <Tinymce ref="editor" v-model="postForm.blogContent" :height="400" /> -->
          <!-- markdown编辑器 -->
          <mavon-editor
            ref="editor"
            v-model="postForm.blogContent"
            :height="400"
            style="position:static"
          />
          <!-- <markdown-editor ref="markdownEditor" v-model="postForm.blogContent" :language="lang" height="500px" width="300px" /> -->
        </el-form-item>

        <!-- 图片 -->
        <el-form-item prop="image_uri" style="margin-bottom: 30px;">
          <Upload v-model="postForm.imageBase64Str" />
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
// import MarkdownEditor from '@/components/MarkdownEditor'
// import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/SingleImage3'
import DynamicTags from '@/components/DynamicTags'
import MDinput from '@/components/MDinput'
import Sticky from '@/components/Sticky' // 粘性header组件
import { validURL } from '@/utils/validate'
import { getBlogDetail, saveBlog } from '@/api/article'
import { searchUser, searchBlogCategory } from '@/api/remote-search'
import Warning from './Warning'
import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown
} from './Dropdown'
import { formatTime } from '@/utils/time.js'

const defaultForm = {
  blogStatus: 0, // 0：草稿，1：已发布
  title: '', // 文章题目
  blogContent: '', // 文章内容
  blogTitle: '', // 文章摘要
  source_uri: '', // 文章外链
  blogCoverImage: '', // 文章图片
  publishTime: undefined, // 前台展示时间
  id: undefined,
  blogTags: [],
  importance: 0,
  blogSubUrl: '', // 文章路径
  enableComment: true, // false:不允许评论，true：允许评论
  blogCategoryId: undefined, // 分类
  createUser: ''
}

export default {
  name: 'ArticleDetail',
  components: {
    MDinput,
    Upload,
    Sticky,
    Warning,
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown,
    DynamicTags
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isChange: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === '') {
        this.$message({
          message: rule.field + '为必传项',
          type: 'error'
        })
        callback(new Error(rule.field + '为必传项'))
      } else {
        callback()
      }
    }
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback()
        } else {
          this.$message({
            message: '外链url填写不正确',
            type: 'error'
          })
          callback(new Error('外链url填写不正确'))
        }
      } else {
        callback()
      }
    }
    return {
      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      categoryMapOptions: [],
      rules: {
        image_uri: [{ validator: validateRequire }],
        blogTitle: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: 'blur' }]
      },
      tempRoute: {},
      requestParam: {}
    }
  },
  computed: {
    contentShortLength() {
      return this.postForm.blogTitle.length
    },
    lang() {
      return this.$store.getters.language
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return formatTime(this.postForm.publishTime, 'yyyy-MM-dd HH:mm:ss')
      },
      set(val) {
        this.postForm.publishTime = formatTime(new Date(val), 'yyyy-MM-dd HH:mm:ss')
      }
    }
  },
  created() {
    if (this.isEdit) {
      this.requestParam.id = this.$route.params && this.$route.params.id
      this.fetchData(this.requestParam)
    } else {
      // 新建博客
      this.postForm.createUser = this.$store.getters.name
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route)

    // 获取分类列表
    searchBlogCategory().then((response) => {
      if (!response.data) return
      this.categoryMapOptions = response.data
    })
  },
  // watch:{
  //   displayTime.: {
  //     handler () { //这是vue的规定写法，当你watch的值发生变化的时候，就会触发这个handler，这是vue内部帮你做的事情
  //       console.log("watch！！！！")
  //     },
  //     deep: true,  // 可以深度检测到 obj 对象的属性值的变化
  //     immediate: true //刷新加载  立马触发一次handler
  //   }
  // },
  methods: {
    fetchData(requestParam) {
      getBlogDetail(requestParam).then((response) => {
        this.postForm = response.data

        // just for test
        this.postForm.title += `   Article Id:${this.postForm.blogId}`
        this.postForm.content_short += `   Article Id:${this.postForm.blogId}`

        // set tagsview title
        this.setTagsViewTitle()

        // set page title
        this.setPageTitle()
      })
        .catch((err) => {
          console.log(err)
        })
    },
    setTagsViewTitle() {
      const title = this.lang === 'zh' ? '编辑文章' : 'Edit Article'
      const route = Object.assign({}, this.tempRoute, {
        title: `${title}-${this.postForm.blogId}`
      })
      this.$store.dispatch('tagsView/updateVisitedView', route)
    },
    setPageTitle() {
      const title = 'Edit Article'
      document.title = `${title} - ${this.postForm.blogId}`
    },
    submitForm() {
      console.log(this.postForm)
      this.$refs.postForm.validate((valid) => {
        if (valid) {
          this.loading = true
          // 弹窗确认
          this.$confirm('保存并发布 或者 直接发布', '确认', {
            // 自定义图标样式
            iconClass: 'el-icon-question',
            // 确认按钮文字更换
            confirmButtonText: '保存并发布',
            // 取消按钮文字更换
            cancelButtonText: '发布',
            // 是否显示右上角关闭按钮
            showClose: true,
            // 提示类型  success/info/warning/error
            type: 'warning'
          }).then(() => {
            this.postForm.blogStatus = 1
            // 确认操作
            this.$notify({
              title: '成功',
              message: '发布文章成功',
              type: 'success',
              duration: 2000
            })
            this.loading = false
            this.postForm = this.defaultForm
          }).catch(() => {
            // 取消操作
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    draftForm() {
      if (this.postForm.blogContent.length === 0 || this.postForm.blogTitle.length === 0) {
        this.$message({
          message: '请填写必要的标题和内容',
          type: 'warning'
        })
        return
      }
      this.loading = true
      // 弹窗确认
      this.$confirm('保存草稿？', '提示', {
        iconClass: 'el-icon-question',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        showClose: true,
        type: 'warning'
      }).then(() => {
        this.postForm.blogStatus = 0
        console.log(this.$store.getters.token)
        // 确认操作
        saveBlog(this.postForm).then((response) => {
          this.loading = false
          this.$message({
            message: '保存成功',
            type: 'success',
            showClose: true,
            duration: 1000
          })
          this.postForm = this.defaultForm
        }).catch(() => {
          this.loading = false
          this.$message({
            message: '保存失败',
            type: 'error',
            showClose: true,
            duration: 1000
          })
        })
      }).catch(() => {
        // 取消操作
        this.loading = false
      })
    },
    getRemoteUserList(query) {
      searchUser(query).then((response) => {
        if (!response.data.items) return
        this.userListOptions = response.data.items
      })
    },
    getBlogCategory(query) {
      this.userListOptions = this.userListOptions.filter((item) => {
        return item.indexOf(query) >= 0
      })
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
</style>
